package mobile.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import mobile.vo.Mode;
import org.apache.commons.lang.StringUtils;
/**
 * http协议工具类
 * @author wangshaoming
 *
 */
public class HttpUtils {
	private static final Pattern pattern = Pattern  
            .compile("http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?");
	/**
	 * get请求
	 * @param url
	 */
	public static Mode doGet(String url){
		InputStream is=null;
		StringBuffer buffer=new StringBuffer(2048);
		BufferedReader br=null;
		try {
			URL urlGet=new URL(url);
			HttpURLConnection http=(HttpURLConnection)urlGet.openConnection();
			http.setRequestMethod("GET");
			http.setReadTimeout(10000);
			http.setConnectTimeout(10000);
			http.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
			http.setDoOutput(true);
			http.setDoInput(true);
			http.connect();
			is=http.getInputStream();
//			if(!"text/html".equals(http.getContentType())){
//				return "";
//			}
			if(http.getResponseCode()==301||http.getResponseCode()==302){
				String name=http.getHeaderField("location");
				Mode mode=new Mode(http.getResponseCode(),name);
				return mode;
			}
			if(http.getResponseCode()==200){
				br=new BufferedReader(new InputStreamReader(is,"UTF-8"));
				String line="";
				while((line=br.readLine())!=null){
					buffer.append(line);
				}
				String message=buffer.toString();
				return new Mode(200,url,message);
			}else{
				return null;
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}finally{
			if(is!=null){
				try {
					is.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				}
			}
			if(br!=null){
				try {
					br.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					return null;
				}
			}
		}
	}
	public static String getUrl(String text){
		Matcher matcher = pattern.matcher(text);
		String url="";
		while (matcher.find()) {
			url=matcher.group(0);
	    }
		if(StringUtils.isEmpty(url)){
			return "";
		}
		Mode cont=doGet(url);
		if(cont.code==200){
			String invadUrl=cont.msg.substring(cont.msg.indexOf("var url =")+"var url =".length(), cont.msg.indexOf("var invalidUrl ="));
			String invaurl=invadUrl.substring(invadUrl.indexOf("'")+1,invadUrl.lastIndexOf("'"));
			if(StringUtils.isEmpty(invaurl)){
				return "";
			}
			cont=doGet(invaurl);
			if(cont!=null){
				return cont.url;
			}
			return "";
		}
		return "";
	}
}
